// import _path from 'path'
// import fs from 'fs'
// import {nativeImage} from 'electron'
// import jsPDF from 'jspdf'
// import ExcelJS from 'exceljs'
import XLSX from 'xlsx'

/**
 * 子线程执行的js模块，需要export一个start()方法
 * 第一个参数data，为调用传参
 * data = {
 *  filename: filename,
 *  fileList: this.fileList,
 *  userConfig: this.userConfig
 * }
 * 第二个参数sendInfo(response)是一个function，执行该函数可向主线程发送消息
 */
export function start (data, sendInfo) {
  return new Promise(async (resolve, reject) => {
    console.log('开始')
    console.log('XLSX.utils.book_new()')
    const resultWookBook = XLSX.utils.book_new()
    console.log('resultWookBook.Sheets.length: ' + resultWookBook.Sheets.length)
    let resultJson = []
    let map = {}
    let single = 0
    data.fileList.forEach((it, n) => {
      console.log('Excel: ' + it.name)
      let workBook = XLSX.readFile(it.path)
      workBook.SheetNames.forEach(sheetName => {
        console.log('sheetName: ' + sheetName)
        let workSheet = workBook.Sheets[sheetName]
        let data = XLSX.utils.sheet_to_json(workSheet)
        console.log(data)
        data.forEach(it => {
          let number = it['混检编号']
          if (!number) {
            single++
          } else if (!map[number]) {
            map[number] = 1
          } else {
            map[number]++
          }
        })
        resultJson.push(...data)
        console.log('resultJson.length: ' + resultJson.length)
        console.log(map)
        console.log('single: ' + single)
      })
      sendInfo && sendInfo((n + 1) / data.fileList.length)
    })
    let resMap = {}
    for (let k in map) {
      let v = map[k]
      if (!resMap[v]) {
        resMap[v] = 1
      } else {
        resMap[v]++
      }
    }
    let t5 = 0
    let t10 = 0
    let t20 = 0
    let total = 0
    let list = []
    for (let k in resMap) {
      let v = resMap[k]
      let type = 0
      if (k > 0 && k <= 5) {
        t5 += v
        type = 5
      } else if (k > 5 && k <= 10) {
        t10 += v
        type = 10
      } else if (k > 10) {
        t20 += v
        type = 20
      }
      total += v
      list.push({
        peopleNum: k + '人',
        tubeNum: v,
        type: type
      })
    }
    list.forEach(it => {
      if (it.type === 5) {
        it.sum = t5
      } else if (it.type === 10) {
        it.sum = t10
      } else if (it.type === 20) {
        it.sum = t20
      }
    })
    list.push({
      peopleNum: '单检',
      tubeNum: single,
      sum: single,
      type: '单检'
    })
    total += single
    list.push({
      peopleNum: '合计',
      tubeNum: total,
      sum: total,
      type: '合计'
    })
    resolve({
      single: single,
      map: map,
      resMap: resMap,
      t5: t5,
      t10: t10,
      t20: t20,
      total: total,
      list: list
    })
  })
}
